<template>
  <div class="wheat-data">
    <div class="action-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索样本编号、产地或检测员"
          style="width: 300px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="qualityFilter" placeholder="品质等级" style="width: 120px; margin-left: 12px;">
          <el-option label="全部" value="" />
          <el-option label="优质" value="excellent" />
          <el-option label="良好" value="good" />
          <el-option label="一般" value="normal" />
          <el-option label="较差" value="poor" />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px; margin-left: 12px;"
        />
      </div>
      
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDataDialog">
          <el-icon><Plus /></el-icon>
          添加数据
        </el-button>
        <el-button @click="importData">
          <el-icon><Upload /></el-icon>
          导入数据
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <input type="file" ref="fileInputRef" accept=".csv" style="display:none" @change="handleFileChange" />
      </div>
    </div>
    
    <el-table :data="paginatedData" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="样本编号" width="120" />
      <el-table-column prop="origin" label="产地" width="150" />
      <el-table-column prop="variety" label="品种" width="120" />
      <el-table-column prop="harvestDate" label="收获日期" width="120" />
      <el-table-column prop="protein" label="蛋白质(%)" width="100" />
      <el-table-column prop="moisture" label="水分(%)" width="100" />
      <el-table-column prop="ash" label="灰分(%)" width="100" />
      <el-table-column prop="gluten" label="面筋(%)" width="100" />
      <el-table-column prop="quality" label="品质等级" width="100">
        <template #default="{ row }">
          <el-tag :type="getQualityType(row.quality)" size="small">
            {{ getQualityLabel(row.quality) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="inspector" label="检测员" width="100" />
      <el-table-column prop="testDate" label="检测日期" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="viewDetail(row)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button type="text" size="small" @click="openEditDataDialog(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="text" size="small" @click="deleteData(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 新增/编辑数据对话框 -->
    <el-dialog :title="dataDialogTitle" v-model="dataDialogVisible" width="640px" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRules" ref="dataFormRef" label-width="120px">
        <el-form-item label="样本编号" prop="id">
          <el-input v-model="dataForm.id" placeholder="例如：WH2024008" :disabled="dialogMode==='edit'" />
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="dataForm.origin" placeholder="请输入产地" />
        </el-form-item>
        <el-form-item label="品种" prop="variety">
          <el-input v-model="dataForm.variety" placeholder="请输入品种" />
        </el-form-item>
        <el-form-item label="收获日期" prop="harvestDate">
          <el-date-picker v-model="dataForm.harvestDate" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="蛋白质(%)" prop="protein">
          <el-input v-model.number="dataForm.protein" placeholder="12.5" />
        </el-form-item>
        <el-form-item label="水分(%)" prop="moisture">
          <el-input v-model.number="dataForm.moisture" placeholder="13.2" />
        </el-form-item>
        <el-form-item label="灰分(%)" prop="ash">
          <el-input v-model.number="dataForm.ash" placeholder="1.8" />
        </el-form-item>
        <el-form-item label="面筋(%)" prop="gluten">
          <el-input v-model.number="dataForm.gluten" placeholder="28.5" />
        </el-form-item>
        <el-form-item label="品质等级" prop="quality">
          <el-select v-model="dataForm.quality" placeholder="选择品质等级" style="width: 100%;">
            <el-option label="优质" value="excellent" />
            <el-option label="良好" value="good" />
            <el-option label="一般" value="normal" />
            <el-option label="较差" value="poor" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测员" prop="inspector">
          <el-input v-model="dataForm.inspector" placeholder="请输入检测员" />
        </el-form-item>
        <el-form-item label="检测日期" prop="testDate">
          <el-date-picker v-model="dataForm.testDate" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dataDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/plugins/axios'

export default {
  name: 'WheatData',
  setup() {
    const loading = ref(false)
    const searchKeyword = ref('')
    const qualityFilter = ref('')
    const dateRange = ref([])
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    
    const wheatData = ref([
      {
        id: 'WH2024001',
        origin: '河南省郑州市',
        variety: '郑麦366',
        harvestDate: '2024-06-15',
        protein: 12.5,
        moisture: 13.2,
        ash: 1.8,
        gluten: 28.5,
        quality: 'excellent',
        inspector: '张三',
        testDate: '2024-06-20'
      },
      {
        id: 'WH2024002',
        origin: '山东省济南市',
        variety: '济麦22',
        harvestDate: '2024-06-10',
        protein: 11.8,
        moisture: 14.1,
        ash: 1.9,
        gluten: 26.2,
        quality: 'good',
        inspector: '李四',
        testDate: '2024-06-18'
      },
      {
        id: 'WH2024003',
        origin: '河北省石家庄市',
        variety: '石麦15',
        harvestDate: '2024-06-12',
        protein: 10.5,
        moisture: 15.3,
        ash: 2.1,
        gluten: 24.8,
        quality: 'normal',
        inspector: '王五',
        testDate: '2024-06-22'
      }
    ])
    
    const filteredData = computed(() => {
      let filtered = wheatData.value
      
      if (searchKeyword.value) {
        filtered = filtered.filter(item => 
          item.id.includes(searchKeyword.value) ||
          item.origin.includes(searchKeyword.value) ||
          item.inspector.includes(searchKeyword.value)
        )
      }
      
      if (qualityFilter.value) {
        filtered = filtered.filter(item => item.quality === qualityFilter.value)
      }
      
      if (Array.isArray(dateRange.value) && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
        const [start, end] = dateRange.value
        const startTime = new Date(start).getTime()
        const endTime = new Date(end).getTime()
        filtered = filtered.filter(item => {
          const t = new Date(item.testDate).getTime()
          return t >= startTime && t <= endTime
        })
      }
      return filtered
    })

    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      total.value = filteredData.value.length
      return filteredData.value.slice(start, end)
    })
    
    const getQualityType = (quality) => {
      const types = {
        excellent: 'success',
        good: 'primary',
        normal: 'warning',
        poor: 'danger'
      }
      return types[quality] || 'info'
    }
    
    const getQualityLabel = (quality) => {
      const labels = {
        excellent: '优质',
        good: '良好',
        normal: '一般',
        poor: '较差'
      }
      return labels[quality] || '未知'
    }
    
    const dataDialogVisible = ref(false)
    const dialogMode = ref('add')
    const dataFormRef = ref(null)
    const dataForm = reactive({
      id: '',
      origin: '',
      variety: '',
      harvestDate: '',
      protein: null,
      moisture: null,
      ash: null,
      gluten: null,
      quality: '',
      inspector: '',
      testDate: ''
    })
    const dataRules = {
      id: [{ required: true, message: '请输入样本编号', trigger: 'blur' }],
      origin: [{ required: true, message: '请输入产地', trigger: 'blur' }],
      variety: [{ required: true, message: '请输入品种', trigger: 'blur' }],
      harvestDate: [{ required: true, message: '请选择收获日期', trigger: 'change' }],
      protein: [{ required: true, message: '请输入蛋白质', trigger: 'blur' }],
      moisture: [{ required: true, message: '请输入水分', trigger: 'blur' }],
      ash: [{ required: true, message: '请输入灰分', trigger: 'blur' }],
      gluten: [{ required: true, message: '请输入面筋', trigger: 'blur' }],
      quality: [{ required: true, message: '请选择品质等级', trigger: 'change' }],
      inspector: [{ required: true, message: '请输入检测员', trigger: 'blur' }],
      testDate: [{ required: true, message: '请选择检测日期', trigger: 'change' }]
    }
    const dataDialogTitle = computed(() => (dialogMode.value === 'add' ? '添加数据' : '编辑数据'))

    const resetDataForm = () => {
      dataForm.id = ''
      dataForm.origin = ''
      dataForm.variety = ''
      dataForm.harvestDate = ''
      dataForm.protein = null
      dataForm.moisture = null
      dataForm.ash = null
      dataForm.gluten = null
      dataForm.quality = ''
      dataForm.inspector = ''
      dataForm.testDate = ''
    }

    const openAddDataDialog = () => {
      dialogMode.value = 'add'
      resetDataForm()
      dataDialogVisible.value = true
    }
    
    const fileInputRef = ref(null)
    const importData = () => { fileInputRef.value?.click() }
    const handleFileChange = (e) => {
      const file = e.target.files?.[0]
      if (!file) return
      const reader = new FileReader()
      reader.onload = () => {
        try {
          const text = reader.result
          const lines = String(text).split(/\r?\n/).filter(Boolean)
          const headers = lines.shift().split(',').map(h => h.trim())
          const items = lines.map(line => {
            const cells = line.split(',')
            const obj = {}
            headers.forEach((h, idx) => { obj[h] = cells[idx] })
            return obj
          })
          const existingIds = new Set(wheatData.value.map(d => d.id))
          items.forEach(item => { if (!existingIds.has(item.id)) wheatData.value.push(item) })
          ElMessage.success(`成功导入 ${items.length} 条数据（本地）`)
        } catch (err) {
          ElMessage.error('导入失败，请检查文件格式')
        } finally {
          e.target.value = ''
        }
      }
      reader.readAsText(file, 'utf-8')
    }
    
    const exportData = () => {
      const rows = filteredData.value
      if (!rows.length) { ElMessage.info('无可导出的数据'); return }
      const headers = ['id','origin','variety','harvestDate','protein','moisture','ash','gluten','quality','inspector','testDate']
      const csv = [headers.join(',')]
      rows.forEach(r => csv.push(headers.map(h => (r[h] ?? '')).join(',')))
      const blob = new Blob(["\ufeff" + csv.join('\n')], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `wheat-data-${Date.now()}.csv`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      ElMessage.success('导出完成')
    }
    
    const viewDetail = (row) => {
      ElMessage.info('查看详情功能开发中...')
    }
    
    const openEditDataDialog = (row) => {
      dialogMode.value = 'edit'
      Object.assign(dataForm, row)
      dataDialogVisible.value = true
    }

    const submitData = async () => {
      dataFormRef.value?.validate(async (valid) => {
        if (!valid) return
        try {
          if (dialogMode.value === 'add') {
            const resp = await axios.post('/wheat/add', { ...dataForm })
            if (resp?.data?.code === 1) {
              ElMessage.success('添加成功')
              await fetchWheatData()
              dataDialogVisible.value = false
              return
            }
            wheatData.value.unshift({ ...dataForm })
            ElMessage.success('添加成功（本地）')
            dataDialogVisible.value = false
          } else {
            const resp = await axios.post('/wheat/update', { ...dataForm })
            if (resp?.data?.code === 1) {
              ElMessage.success('保存成功')
              await fetchWheatData()
              dataDialogVisible.value = false
              return
            }
            const idx = wheatData.value.findIndex(d => d.id === dataForm.id)
            if (idx !== -1) wheatData.value[idx] = { ...dataForm }
            ElMessage.success('保存成功（本地）')
            dataDialogVisible.value = false
          }
        } catch (e) {
          if (dialogMode.value === 'add') {
            wheatData.value.unshift({ ...dataForm })
            ElMessage.success('添加成功（本地）')
          } else {
            const idx = wheatData.value.findIndex(d => d.id === dataForm.id)
            if (idx !== -1) wheatData.value[idx] = { ...dataForm }
            ElMessage.success('保存成功（本地）')
          }
          dataDialogVisible.value = false
        }
      })
    }
    
    const deleteData = (row) => {
      ElMessageBox.confirm(
        `确定要删除样本 "${row.id}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const resp = await axios.post(`/wheat/delete/${row.id}`)
          if (resp?.data?.code === 1) {
            ElMessage.success('删除成功')
            await fetchWheatData()
            return
          }
        } catch (e) { /* ignore */ }
        const index = wheatData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          wheatData.value.splice(index, 1)
          ElMessage.success('数据删除成功（本地）')
        }
      }).catch(() => {})
    }

    // 注意：已在上方声明 fileInputRef
    
    const fetchWheatData = async () => {
      loading.value = true
      try {
        const params = { pageNum: currentPage.value, pageSize: pageSize.value }
        const search = {}
        if (searchKeyword.value) search.keyword = searchKeyword.value
        if (qualityFilter.value) search.quality = qualityFilter.value
        const resp = await axios.post('/wheat/list', search, { params })
        if (resp?.data?.code === 1) {
          const records = resp.data.data.records || []
          total.value = resp.data.data.total || records.length
          wheatData.value = records
        }
      } catch (e) { /* ignore */ }
      finally { loading.value = false }
    }

    onMounted(() => fetchWheatData())

    return {
      loading,
      searchKeyword,
      qualityFilter,
      dateRange,
      currentPage,
      pageSize,
      total,
      filteredData,
      paginatedData,
      getQualityType,
      getQualityLabel,
      dataDialogVisible,
      dataDialogTitle,
      dialogMode,
      dataForm,
      dataRules,
      dataFormRef,
      openAddDataDialog,
      openEditDataDialog,
      submitData,
      importData,
      handleFileChange,
      fileInputRef,
      exportData,
      viewDetail,
      deleteData
    }
  }
}
</script>

<style scoped>
.wheat-data {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.search-area {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
